<template>
  <div class='container'>
    <el-dialog :visible="showDialog" @close="closeDialog">
    <div slot="title" style="color:white">{{ showTitle }}</div>
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item v-show="!$route.query.id" label="所属学科" prop="subjectID" label-width="100px">
        <el-select v-model="form.subjectID" placeholder="请选择">
          <el-option
          v-for="item in subjectList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="目录名称" prop="directoryName" label-width="100px">
        <el-input v-model="form.directoryName" autocomplete="off" placeholder="请输入目录名称"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="beforeSubmit">确 定</el-button>
    </div>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/directorys'
import { simple } from '@/api/hmmm/subjects'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    directInfo: {
      type: Object,
      default: null
    }
  },
  data () {
    return {
      form: {
        id: null,
        subjectID: null,
        directoryName: ''
      },
      rules: {
        subjectID: [{ required: true, message: '请选择科目', trigger: 'change' }],
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' },
          { min: 2, max: 8, message: '目录名称2-8字符', trigger: 'blur' }
        ]
      },
      subjectList: []
    }
  },
  computed: {
    showTitle () {
      return this.form.id ? '编辑目录' : '新增目录'
    }
  },
  watch: {
    directInfo (val) {
      this.form = val
    },
    showDialog (val) {
      if (val) {
        this.getSimpleSub()
        this.form.subjectID = +this.$route.query.id || +this.directInfo.subjectID || null
      }
    }
  },
  methods: {
    closeDialog () {
      this.form = {
        id: null,
        subjectID: '',
        directoryName: ''
      }
      this.$refs.form.resetFields()
      this.$emit('update:showDialog', false)
    },
    async getSimpleSub () {
      const { data } = await simple()
      this.subjectList = data
    },
    beforeSubmit () {
      this.$refs.form.validate(isValid => {
        if (isValid) {
          this.handleSubmit()
        } else {
          return false
        }
      })
    },
    async handleSubmit () {
      if (this.form.id) {
        await update(this.form)
      } else {
        await add(this.form)
      }
      this.form = {
        id: null,
        subjectID: '',
        directoryName: ''
      }
      this.$emit('update:showDialog', false)
      this.$emit('refresh')
    }
  }
}
</script>

<style scoped lang='scss'>
  ::v-deep .el-dialog{
    width: 30%;
  }
</style>
